<template>
  <div class="search">
    <form action="/">
      <van-search
        v-model.trim="value"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="$router.back()"
        background="#3296fa"
        @focus="isShowRes = false"
      />
      <search-results v-if="isShowRes" :searchText="value"></search-results>
      <search-history
        @onSearch="onSearch"
        v-else-if="!value"
        :history="history"
        @clear="history = []"
      ></search-history>
      <search-suggestion
        v-else
        :searchText="value"
        @onSearch="onSearch"
      ></search-suggestion>
    </form>
  </div>
</template>

<script>
import SearchHistory from './components/SearchHistory'
import SearchResults from './components/SearchResults'
import SearchSuggestion from './components/SearchSuggestion'
import { getStorage, setStorage } from '@/utils/storage.js'
export default {
  components: { SearchHistory, SearchResults, SearchSuggestion },
  name: 'search',
  data () {
    return {
      value: '',
      isShowRes: false,
      history: getStorage('TT-HISTORY') || []
    }
  },

  created () {},
  watch: {
    history: {
      deep: true,
      handler (val) {
        setStorage('TT-HISTORY', val)
      }
    }
  },

  methods: {
    onSearch (val) {
      this.value = val
      this.isShowRes = true
      this.history.unshift(val)
      this.history = [...new Set(this.history)]
    }
  }
}
</script>

<style scoped lang="less">
.search {
  .van-search__action {
    color: #fff;
  }
}
</style>
